"""
主程序 - 交互式ReActAgent对话系统

展示完整的使用流程：
1. 初始化配置
2. 创建工具集（包括MCP和自定义工具）
3. 创建ReActAgent
4. 交互式对话
"""
import asyncio
from agentscope.message import Msg
from loguru import logger

from settings import settings
from agents.mcp.client import MCPClientManager
from agents.tools.toolkit_manager import ToolkitManager
from agents.clients.react_agent_client import ReActAgentClient


def print_tools(toolkit_manager: ToolkitManager):
    """打印所有可用工具"""
    print("\n" + "=" * 80)
    print("📦 当前可用工具列表")
    print("=" * 80)
    
    schemas = toolkit_manager.toolkit.get_json_schemas()
    
    if not schemas:
        print("  ⚠️  暂无可用工具")
        return
    
    # 按工具组分组显示
    tools_by_group = {}
    for schema in schemas:
        func_info = schema.get("function", {})
        name = func_info.get("name", "未知")
        description = func_info.get("description", "无描述")
        
        # 尝试从名称推断工具组
        if name.startswith("mcp_"):
            group = "MCP工具"
        else:
            group = "自定义工具"
        
        if group not in tools_by_group:
            tools_by_group[group] = []
        
        tools_by_group[group].append({
            "name": name,
            "description": description
        })
    
    # 显示工具
    for group_name, tools in tools_by_group.items():
        print(f"\n🔧 {group_name} ({len(tools)} 个):")
        for i, tool in enumerate(tools, 1):
            print(f"  {i}. {tool['name']}")
            print(f"     └─ {tool['description']}")
    
    print(f"\n总计: {len(schemas)} 个工具")
    print("=" * 80)


async def interactive_chat(agent_client: ReActAgentClient):
    """交互式对话循环"""
    print("\n" + "=" * 80)
    print("💬 进入交互式对话模式")
    print("=" * 80)
    print("提示:")
    print("  - 输入你的问题开始对话")
    print("  - 输入 'exit' 或 'quit' 退出")
    print("  - 输入 'clear' 清空对话历史")
    print("  - 输入 'state' 查看Agent状态")
    print("=" * 80 + "\n")
    
    messages = []
    
    while True:
        try:
            # 获取用户输入
            user_input = input("\n👤 你: ").strip()
            
            if not user_input:
                continue
            
            # 处理特殊命令
            if user_input.lower() in ['exit', 'quit', '退出']:
                print("\n👋 再见！")
                break
            
            elif user_input.lower() in ['clear', '清空']:
                messages = []
                print("✅ 对话历史已清空")
                continue
            
            elif user_input.lower() in ['state', '状态']:
                state = await agent_client.get_state()
                print(f"\n📊 Agent状态:")
                print(f"  - 名称: {state.agent_name}")
                print(f"  - 工具数量: {state.tool_count}")
                print(f"  - 记忆大小: {state.memory_size} 条消息")
                print(f"  - 长期记忆: {'启用' if state.long_term_memory_enabled else '禁用'}")
                continue
            
            # 添加用户消息
            messages.append(
                Msg(name="用户", content=user_input, role="user")
            )
            
            # 获取Agent响应
            print("\n🤖 Agent: ", end="", flush=True)
            
            assistant_response = ""
            
            async for response in agent_client.chat_stream(messages):
                if response.code == 200:
                    content = response.content
                    
                    if content.type == "text" and content.text:
                        print(content.text, end="", flush=True)
                        assistant_response += content.text
                    
                    elif content.type == "tool_use" and content.tool_use_name:
                        tool_msg = f"\n  🔧 [调用工具: {content.tool_use_name}]"
                        print(tool_msg, end="", flush=True)
                    
                    elif content.type == "tool_result" and content.tool_result_output:
                        result_msg = f"\n  ✓ [工具返回: {len(content.tool_result_output)} 条结果]"
                        print(result_msg, end="", flush=True)
                else:
                    error_msg = f"\n❌ 错误: {response.content.error}"
                    print(error_msg)
                    assistant_response = error_msg
            
            print()  # 换行
            
            # 保存assistant响应到消息历史（简化版本）
            if assistant_response:
                messages.append(
                    Msg(name="助手", content=assistant_response, role="assistant")
                )
        
        except KeyboardInterrupt:
            print("\n\n👋 收到中断信号，退出...")
            break
        except Exception as e:
            logger.error(f"对话出错: {e}")
            print(f"\n❌ 发生错误: {e}")


async def main():
    """主函数"""
    
    # 1. 显示配置信息
    print("\n" + "=" * 80)
    print("🚀 AgentScope ReActAgent 交互式系统")
    print("=" * 80)
    print(f"🤖 模型: {settings.QWEN_MODEL_NAME}")
    print(f"👤 Agent名称: {settings.AGENT_NAME}")
    print(f"🧠 思考模式: {'启用' if settings.ENABLE_THINKING else '禁用'}")
    print(f"💾 长期记忆: {'启用' if settings.ENABLE_LONG_TERM_MEMORY else '禁用'}")
    print(f"⚡ 并行工具调用: {'启用' if settings.PARALLEL_TOOL_CALLS else '禁用'}")
    print("=" * 80)
    
    # 2. 创建工具集管理器
    toolkit_manager = ToolkitManager()
    
    # 3. 注册自定义工具（已禁用，仅测试MCP工具）
    # logger.info("注册自定义工具...")
    # toolkit_manager.register_custom_tools(group_name="custom_tools")
    # logger.info(f"✅ 已注册 {len(toolkit_manager.list_tools())} 个自定义工具")
    logger.info("⚠️  已跳过本地自定义工具注册，仅测试MCP工具")
    
    # 4. 注册MCP工具（如果配置了MCP服务器）
    if settings.MCP_SERVER_URL:
        logger.info("注册MCP工具...")
        try:
            mcp_client = MCPClientManager(
                name="mcp_service",
                url=settings.MCP_SERVER_URL,
                transport=settings.MCP_TRANSPORT,
                stateful=False  # 使用无状态客户端
            )
            
            await toolkit_manager.register_mcp_client(
                mcp_client.get_client(),
                group_name="mcp_tools"
            )
            logger.info(f"✅ MCP工具注册完成，总工具数: {toolkit_manager.get_tool_count()}")
        except Exception as e:
            logger.warning(f"⚠️  MCP工具注册失败（跳过）: {e}")
            logger.info("将继续使用本地工具...")
    else:
        logger.info("未配置MCP服务器，跳过MCP工具注册")
    
    # 5. 创建ReActAgent客户端
    logger.info("创建ReActAgent客户端...")
    agent_client = ReActAgentClient(
        username="用户",
        toolkit_manager=toolkit_manager
    )
    logger.info("✅ Agent客户端创建完成")
    
    # 6. 显示Agent状态
    state = await agent_client.get_state()
    print(f"\n📊 Agent初始状态:")
    print(f"  - 名称: {state.agent_name}")
    print(f"  - 工具数量: {state.tool_count}")
    print(f"  - 记忆大小: {state.memory_size}")
    print(f"  - 长期记忆: {'启用' if state.long_term_memory_enabled else '禁用'}")
    
    # 7. 显示所有可用工具
    print_tools(toolkit_manager)
    
    # 8. 进入交互式对话
    await interactive_chat(agent_client)
    
    # 9. 显示最终状态
    final_state = await agent_client.get_state()
    print("\n" + "=" * 80)
    print("📊 最终Agent状态:")
    print(f"  - 记忆大小: {final_state.memory_size} 条消息")
    print("=" * 80)
    
    logger.info("程序结束！")


if __name__ == "__main__":
    # 运行主函数
    asyncio.run(main())
